<script setup>
import { SPLITPANEL_INJECTION_KEY } from '@/components/SplitPanel/splitPanel.js'
import { computed, getCurrentInstance, inject, onBeforeUnmount, reactive, ref, shallowRef, unref } from 'vue'

defineOptions({
  name: 'SplitPanelItem',
})

// const props = reactive({
//   space: 0,
// })
const props = defineProps({
  space: {
    type: [String, Number],
    default: '',
  },
  panelItemClass: {
    type: String,
    default: '',
  },
})
const el = ref(null)
// 获取父组件的 provide 数据
const SplitPanelContext = inject(SPLITPANEL_INJECTION_KEY)

// refs 和 reactive 数据
const laySplitPanelItem = shallowRef(null)
const index = ref(-1)
const currentInstance = getCurrentInstance()
const moveStatus = ref(false)

// 设置当前步骤的索引
function setIndex(val) {
  index.value = val
}

// 计算 space 的值
const space = computed(() => {
  return /^\d+$/.test(`${props.space}`) ? `${props.space}px` : props.space
})

// 鼠标事件
function mouseup(event) {
  moveStatus.value = false
}

function mousedown(event) {
  moveStatus.value = true
  SplitPanelContext.moveChange(event, true, isVertical.value)
}

// 计算是否为竖向模式
const isVertical = computed(() => {
  return SplitPanelContext.props.vertical
})

// 计算当前是否为第一个步骤
const isStart = computed(() => {
  return unref(SplitPanelContext.steps.value[0]?.itemId) === currentInstance.uid
})

// 步骤项状态
const stepItemState = reactive({
  itemId: computed(() => currentInstance?.uid),
  setIndex,
  space,
  itemEl: laySplitPanelItem,
})

// 向父组件的 steps 中添加当前步骤项
SplitPanelContext.steps.value = [
  ...SplitPanelContext.steps.value,
  stepItemState,
]

// 组件销毁前清理步骤项
onBeforeUnmount(() => {
  SplitPanelContext.steps.value = SplitPanelContext.steps.value.filter(
    step => step.itemId.value !== currentInstance.uid,
  )
})
</script>

<template>
  <div
    v-if="!isStart"
    ref="el"
    :class="[!isStart ? `lay-split-panel-line` : '']"
    v-on="{ mousedown, mouseup }"
  />
  <div
    v-if="isVertical"
    ref="laySplitPanelItem"
    class="lay-split-panel-item"
    :class="panelItemClass"
  >
    <slot />
  </div>
  <div v-else ref="laySplitPanelItem" class="lay-split-panel-item" :class="panelItemClass">
    <slot />
  </div>
</template>
